package com.ww.ll;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.NIOFSDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Version;

import com.chenlb.mmseg4j.analysis.MMSegAnalyzer;

public abstract class LuceneBase {
	protected static final String FIELD_NAME_KEY = "key";
	protected static final String FIELD_NAME_FS_PATH = "fsPath";
	protected static final String FIELD_NAME_FS_NAME = "fsName";
	protected static final String FIELD_NAME_CONTENT = "content";
	
	static{
		
	}
	
	protected Analyzer getAnalyzer(){
		// 分词器 使用默认停止词 去掉标点等
		//return new SmartChineseAnalyzer(Version.LUCENE_40, true);
		//return new MMSegAnalyzer();
		return new SmartChineseProvider().getAnalyzer();
	}
	
	protected Directory getIndexDir() throws IOException{
		return new NIOFSDirectory(new File( 
				getClassPathBase().getParentFile()
				, "docIndex"));
	}
	
	protected File getClassPathBase(){
		try{
			return new File(this.getClass().getResource("/").toURI());
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	protected static String computeMd5Str(File file) throws IOException{
		return DigestUtils.md5Hex(IOUtils.toByteArray(new FileInputStream(file)));
	}
	
	protected static byte[] computeMd5(File file) throws IOException{
		return DigestUtils.md5(IOUtils.toByteArray(new FileInputStream(file)));
	}
	
	protected static BytesRef computeMd5L(File file) throws IOException{
		return new BytesRef(computeMd5(file));
	}
	
	public static String[] split(Analyzer a, String info){
		StringReader sr = new StringReader(info);
		
		TokenStream ts;
		CharTermAttribute termAttr;
		List<String> result = new ArrayList<String>();
		try{
			ts = a.tokenStream(null, sr);
			termAttr = ts.getAttribute(CharTermAttribute.class);
			while(ts.incrementToken()){
				result.add(termAttr.toString());
			}
			return result.toArray(new String[0]);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
